package model

import (
	"errors"
	"go-vue/admin/conf"
	"go-vue/admin/utils"
)

// UserMember 用户管理
type UserMember struct {
	Uid           int64      `xorm:"autoincr uid" json:"uid"`
	UserName      string     `xorm:"user_name" json:"user_name"`
	DepartId      int64      `xorm:"depart_id" json:"depart_id"`
	RoleId        int64      `xorm:"role_id" json:"role_id"`
	Mobile        string     `xorm:"mobile" json:"mobile"`
	RealName      string     `xorm:"real_name" json:"real_name"`
	UserPassword  string     `xorm:"user_password" json:"-"`
	Email         string     `xorm:"email" json:"email"`
	CreateTime    string     `xorm:"create_time" json:"create_time"`
	UpdateTime    string     `xorm:"update_time" json:"update_time"`
	LastLoginTime string     `xorm:"last_login_time" json:"last_login_time"`
	LoginTime     string     `xorm:"login_time" json:"login_time"`
	State         conf.State `xorm:"state" json:"state"`
	Salt          string     `xorm:"salt" json:"-"`
}

// SetUserMemberPwd 用户管理 修改密码
type SetUserMemberPwd struct {
	Uid            int64  `json:"uid"`
	SetType        string `json:"set_type"`
	Password       string `json:"password"`
	RepeatPassword string `json:"repeat_password"`
}

func (member *UserMember) One() *UserMember {
	exist, err := conf.DbEngine.Get(member)
	if err != nil || exist == false {
		return nil
	}
	return member
}

func (member *UserMember) Update() *UserMember {
	_, err := conf.DbEngine.Where("uid = ? " ,member.Uid ).Update(member)
	if err != nil {
		return nil
	}
	return member
}

// GetAllMember 获取所有用户列表 分页
func (member *UserMember) GetAllMember(pagination *PaginationInput) *PaginationOutPut {
	list := make([]UserMember, 0)
	condition, err := GetQuerySearchInput(pagination)
	if err != nil {
		return nil
	}
	err = conf.DbEngine.Where(condition).Limit(pagination.PageSize, pagination.Start).Find(&list)
	if err != nil {
		return nil
	}

	count, err := conf.DbEngine.Where(condition).Count(&UserMember{})
	if err != nil {
		return nil
	}
	output := &PaginationOutPut{
		Rows:    list,
		Total:   count,
		Summary: "",
	}
	return output
}

// SaveEditMember 编辑用户信息
func (member *UserMember) SaveEditMember(input *UserMember) (uid int64, err error) {
	if input.Uid != 0 {
		//更新主表
		input.UpdateTime = utils.DateNowString()
		_, err = conf.DbEngine.Where("uid = ?", input.Uid).Update(input)
		if err != nil {
			return 0, err
		}
		uid = input.Uid
	} else { // 新增
		input.CreateTime = utils.DateNowString()
		input.UpdateTime = utils.DateNowString()
		input.LoginTime = utils.DefaultDateTime
		input.LastLoginTime = utils.DefaultDateTime

		pwd := member.resetPassword("", input.UserName)

		input.Salt = pwd.Salt
		input.UserPassword = pwd.Ciphertext

		_, err = conf.DbEngine.Insert(input)
		if err != nil {
			return 0, err
		}
		uid = input.Uid
	}

	return uid, err
}

// SetPwdEditMember 编辑用户信息
func (member *UserMember) SetPwdEditMember(input *SetUserMemberPwd) (err error) {
	if input.SetType == "reset" {
		pwd := member.resetPassword("", member.UserName)

		member.UserPassword = pwd.Ciphertext
		member.Salt = pwd.Salt

	} else {
		if input.Password == "" || input.Password != input.RepeatPassword {
			return errors.New("两次密码不一致或密码为空")
		}
		member.Uid = input.Uid
		member.One()
		if member.State != conf.StateOn {
			return errors.New("用户不存在或状态不正确")
		}
		member.UserPassword = input.Password
	}

	_, err = conf.DbEngine.Where("uid = ?", input.Uid).Cols("salt,user_password").Update(member)
	return err
}

// resetPassword 重置密码
func (member *UserMember) resetPassword(password, userName string) *utils.PassWord {
	pwd := new(utils.PassWord).MakeSalt()
	if password == "" {
		password = conf.PassWordDefault
	}
	pwd.UserName = userName
	pwd.Plaintext = password
	pwd.Encode()
	return pwd
}

// DelEditUser 删除列表
func (member *UserMember) DelEditUser(input *DeleteInputIds) error {
	if len(input.Ids) == 0 {
		return errors.New("删除数据不存在")
	}
	//删除主表
	_, err := conf.DbEngine.In("uid", input.Ids).Delete(member)
	if err != nil {
		return err
	}
	return nil
}
